// src/utils/menu.js
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

/**
 * 根据路由和权限生成菜单
 */
export const generateMenus = () => {
  const authStore = useAuthStore()
  
  const filterRoutes = (routes, basePath = '') => {
    const menus = []
    
    routes.forEach(route => {
      // 跳过隐藏的路由
      if (route.meta?.hidden) return
      
      // 权限检查
      if (route.meta?.permission && !authStore.hasPermission(route.meta.permission)) {
        console.log(`❌ 菜单权限不足: ${route.path} 需要权限: ${route.meta.permission}`)
        return
      }
      
      const menuItem = {
        name: route.name,
        path: route.path,
        title: route.meta?.title || route.name,
        icon: route.meta?.icon,
        permission: route.meta?.permission,
        children: []
      }
      
      // 处理子路由
      if (route.children && route.children.length > 0) {
        const childMenus = filterRoutes(route.children, route.path)
        
        // 如果有子菜单或者当前菜单项本身有权限，则添加
        if (childMenus.length > 0) {
          menuItem.children = childMenus
          menus.push(menuItem)
        } else if (!route.meta?.permission || authStore.hasPermission(route.meta.permission)) {
          menus.push(menuItem)
        }
      } else {
        // 叶子节点，直接检查权限
        if (!route.meta?.permission || authStore.hasPermission(route.meta.permission)) {
          menus.push(menuItem)
        }
      }
    })
    
    return menus
  }
  
  // 获取主要路由
  const mainRoute = router.options.routes.find(route => route.path === '/')
  
  if (mainRoute && mainRoute.children) {
    const generatedMenus = filterRoutes(mainRoute.children)
    console.log('📋 生成的菜单:', generatedMenus)
    return generatedMenus
  }
  
  return []
}

/**
 * 展平路由为面包屑
 */
export const getBreadcrumbs = (route) => {
  const breadcrumbs = []
  const matched = route.matched.filter(item => item.meta?.title)
  
  matched.forEach(match => {
    breadcrumbs.push({
      title: match.meta.title,
      path: match.path,
      permission: match.meta?.permission
    })
  })
  
  return breadcrumbs
}

/**
 * 检查菜单项是否应该显示
 */
export const shouldShowMenuItem = (menuItem) => {
  const authStore = useAuthStore()
  
  // 如果有权限要求，检查权限
  if (menuItem.permission) {
    return authStore.hasPermission(menuItem.permission)
  }
  
  // 如果有子菜单，检查是否有任何子菜单可以显示
  if (menuItem.children && menuItem.children.length > 0) {
    return menuItem.children.some(child => shouldShowMenuItem(child))
  }
  
  return true
}